/*
 * Copyright 2012 ITC Tsinghua University. All Rights Reserved.
 */
package cn.edu.tsinghua.cic.ccss.bo.impl;

import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.forten.core.dao.rdb.hibernate.HibernateDao;
import org.forten.core.dao.rdb.hibernate.QueryInfo;
import org.forten.core.dao.rdb.query.hql.expression.Compare;
import org.forten.core.dao.rdb.query.hql.expression.Expression;
import org.forten.core.dao.rdb.query.hql.statement.Select;
import org.forten.core.dao.rdb.query.parameter.Param;
import org.forten.core.dao.rdb.query.parameter.Type;
import org.forten.core.dto.GeneralDto;
import org.forten.core.qo.QueryObjectHelper;
import org.forten.core.ro.DtoResultWithPageInfo;
import org.forten.core.ro.PageInfo;
import org.forten.utils.collection.ArrayUtil;
import org.forten.utils.collection.CollectionUtil;
import org.forten.utils.common.DateUtil;
import org.forten.utils.common.StringUtil;
import org.forten.utils.security.MD5Util;
import org.forten.utils.security.TripletsDESUtil;
import org.forten.utils.system.BeanPropertyUtil;
import org.forten.utils.system.LogUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.tsinghua.cic.ccss.bo.CadreBo;
import cn.edu.tsinghua.cic.ccss.bo.SystemSettingBo;
import cn.edu.tsinghua.cic.ccss.dto.CadreDto;
import cn.edu.tsinghua.cic.ccss.dto.CadreDto4Export;
import cn.edu.tsinghua.cic.ccss.dto.CadreDto4ExportSignIn;
import cn.edu.tsinghua.cic.ccss.dto.CadreDto4Import;
import cn.edu.tsinghua.cic.ccss.dto.SuperCadreDto;
import cn.edu.tsinghua.cic.ccss.entity.Cadre;
import cn.edu.tsinghua.cic.ccss.entity.SystemSetting;
import cn.edu.tsinghua.cic.ccss.qo.CadreListQo;

/**
 * 
 * 
 * @author <a href="mailto:du_yi@bbn.cn">Duyi</a>
 * 
 * @since 2012-5-8
 */
@Service("cadreBo")
public class CadreBoImpl implements CadreBo {
	private static Logger log = Logger.getLogger(CadreBoImpl.class);

	@Resource(name = "hibernateDao")
	private HibernateDao hibernateDao;
	@Resource(name = "systemSettingBo")
	private SystemSettingBo systemSettingBo;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * cn.edu.tsinghua.cic.ccss.bo.CadreBo#doUpdate(cn.edu.tsinghua.cic.ccss
	 * .dto.CadreDto)
	 */
	@Override
	@Transactional
	public void doUpdate(CadreDto dto) {
		Cadre entity = hibernateDao.load(Cadre.class, dto.getId());
		entity = encrypt(dto, entity);
		hibernateDao.update(entity);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.edu.tsinghua.cic.ccss.bo.CadreBo#loadCadreDto(java.lang.Long)
	 */
	@Override
	@Transactional(readOnly = true)
	public CadreDto loadCadreDto(Long id) {
		CadreDto dto = new CadreDto();
		Cadre entity = hibernateDao.load(Cadre.class, id);
		dto = decrypt(dto, entity);
		return dto;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * cn.edu.tsinghua.cic.ccss.bo.CadreBo#doSave(cn.edu.tsinghua.cic.ccss.dto
	 * .CadreDto)
	 */
	@Override
	@Transactional
	public String doSave(CadreDto dto) {
		// 若数据库里有此工作证号，则跳过
		QueryInfo qi = new QueryInfo(Cadre.class);
		Expression cardNumEq = Compare.eq(
				"cardNumMD5",
				Param.getCommonParam("cardNumMD5",
						MD5Util.encrypt(dto.getCardNum()), Type.STRING));
		qi.addExpressionsToWhere(cardNumEq);
		qi.setSelect(Select.getCountSelect("id"));
		long count = hibernateDao.getCount(qi);
		if (count > 0) {
			return "[此工作证号在数据库中已存在]";
		}
		Cadre entity = new Cadre();
		entity = encrypt(dto, entity);
		hibernateDao.save(entity);
		try {
			String m = BoHelper.synRoleToAuth(dto.getCardNum());
			LogUtil.info(log, m);
		} catch (MalformedURLException e) {
			return "[同步用户角色失败:" + e.getMessage() + "]";
		} catch (Exception e) {
			return "[同步用户角色失败:" + e.getMessage() + "]";
		}
		return "";
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * cn.edu.tsinghua.cic.ccss.bo.CadreBo#doBatchImport(cn.edu.tsinghua.cic
	 * .ccss.dto.CadreDto[])
	 */
	@Override
	@Transactional
	public List<String> doBatchImport(List<CadreDto4Import> dtoList) {
		List<String> formatErrMsg = new ArrayList<String>();
		LogUtil.info(log, "于%s准备导入干部信息数据",
				DateUtil.convertDateToString(new Date()));
		if (CollectionUtil.isEmpty(dtoList)) {
			formatErrMsg.add("导入数据为空");
			return formatErrMsg;
		}
		//判断导入的Excel 是否含有重复的   工作证号
		List<Cadre> list = new ArrayList<Cadre>(dtoList.size());
		List<String> cardList = new ArrayList<String>(list.size());
		List<Cadre> update_list = new ArrayList<Cadre>();
		for (Cadre cadre : list) {
			cardList.add(cadre.getCardNum());
		}
		
		List<String> realCardList = CollectionUtil
				.getWithoutDuplicatesList(cardList);
		//若 cardList 含有重复工作证号
		if (realCardList.size() < cardList.size()) {
			StringBuilder duplicateCardsMsg = new StringBuilder("导入干部信息的工作证号：[");
			Map<String, Integer> map = new HashMap<String, Integer>();
			for (String card : cardList) {
				if (map.containsKey(card)) {
					map.put(card, map.get(card) + 1);
				} else {
					map.put(card, 1);
				}
			}
			for (String card : map.keySet()) {
				if (map.get(card) > 1) {
					duplicateCardsMsg.append(card);
					duplicateCardsMsg.append(",");
				}
			}
			duplicateCardsMsg.replace(duplicateCardsMsg.length()-1, 1, "]");
			List<String> erroMsg = new ArrayList<String>();
			erroMsg.add(duplicateCardsMsg.toString());
			return erroMsg;
		}
		
		int i = 0;
		for (CadreDto4Import dto : dtoList) {
			if (dto == null) {
				i++;
				continue;
			}
			// 得到格式错误信息
			String errMsg = getFormatErrorMsg(dto);
			// String msg = errMsg;
			// 若数据库里有此工作证号，则跳过
			QueryInfo qi = new QueryInfo(Cadre.class);
			Expression cardNumEq = Compare.eq(
					"cardNumMD5",
					Param.getCommonParam("cardNumMD5",
							MD5Util.encrypt(dto.getCardNum()), Type.STRING));
			qi.addExpressionsToWhere(cardNumEq);
			// 使用查询Cadre实体取代count
			List<Cadre> result = hibernateDao.findEntities(qi);
			Cadre cadre = null;
			if(result.size() > 0){
				cadre = result.get(0);
			}
			
//			qi.setSelect(Select.getCountSelect("id"));
//			long count = hibernateDao.getCount(qi);
			// if (StringUtil.hasText(errMsg) && count > 0) {
			// msg = "第"
			// + (i + 2)
			// + "行数据格式错误："
			// + String.format("[工作证号为%s的干部信息已经在数据库中存在]",
			// dto.getCardNum()) + msg;
			// formatErrMsg.add(msg);
			// i++;
			// continue;
			// }
			// if (!StringUtil.hasText(errMsg) && count > 0) {
			// msg = "第"
			// + (i + 2)
			// + "行数据格式错误："
			// + String.format("[工作证号为%s的干部信息已经在数据库中存在]",
			// dto.getCardNum());
			// formatErrMsg.add(msg);
			// i++;
			// continue;
			// }
			// 判断格式错误信息
			if (StringUtil.hasText(errMsg) && cadre == null) {
				formatErrMsg.add("第" + (i + 2) + "行数据格式错误：" + errMsg);
				i++;
				continue;
			}

			// 若数据库里有此工作证号，则跳过
			// QueryInfo qi = new QueryInfo(Cadre.class);
			// Expression cardNumEq = Compare.eq(
			// "cardNumMD5",
			// Param.getCommonParam("cardNumMD5",
			// MD5Util.encrypt(dto.getCardNum()), Type.STRING));
			// qi.addExpressionsToWhere(cardNumEq);
			// qi.setSelect(Select.getCountSelect("id"));
			// long count = hibernateDao.getCount(qi);
			// if (count > 0) {
			// LogUtil.warn(log,
			// "数据格式错误：工作证号为%s的干部信息已经在数据库中存在，此数据将跳过导入动作，不写入数据库",
			// dto.getCardNum());
			// continue;
			// }
			if(cadre == null){
				Cadre entity = new Cadre();
				entity = encrypt(dto, entity);
				try {
					String m = BoHelper.synRoleToAuth(dto.getCardNum());
					LogUtil.info(log, m);
				} catch (MalformedURLException e) {
					formatErrMsg.add("[同步用户角色失败:" + e.getMessage() + "]");
					return formatErrMsg;
				} catch (Exception e) {
					formatErrMsg.add("[同步用户角色失败:" + e.getMessage() + "]");
					return formatErrMsg;
				}
				list.add(entity);
				i++;
			} else {
				cadre = encrypt(dto, cadre);
				update_list.add(cadre);
			}
		}
		if (!CollectionUtil.isEmpty(formatErrMsg)) {
			return formatErrMsg;
		}
		
		
		if(update_list.size() > 0){
			int update_total = update_list.size();
			hibernateDao.update(update_list.toArray(new Cadre[update_total]));
			LogUtil.info(log, "于%s完成干部信息数据导入，共更新%d条数据",
					DateUtil.convertDateToString(new Date()), update_total);
		}
		if(list.size() > 0){
			int total = list.size();
			hibernateDao.save(list.toArray(new Cadre[total]));
			LogUtil.info(log, "于%s完成干部信息数据导入，共导入%d条数据",
					DateUtil.convertDateToString(new Date()), total);
		}
		return formatErrMsg;
	}

	private String getFormatErrorMsg(CadreDto4Import dto) {
		if (dto == null) {
			return "";
		}
		StringBuilder sb = new StringBuilder();
		if (!StringUtil.hasText(dto.getCardNum())) {
			sb.append("[工作证号不可为空]");
		}
		if (!StringUtil.hasText(dto.getJobLevel())) {
			sb.append("[职级不可为空]");
		}
		if (!StringUtil.isMatch(dto.getJobLevel(), "[1-7]{1}")) {
			sb.append("[职级只能为1到7中的任意数字]");
		}
		if (StringUtil.hasText(dto.getEmail())
				&& !StringUtil
						.isMatch(
								dto.getEmail(),
								"[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})")) {
			sb.append("[Email格式不合法]");
		}
		if (StringUtil.hasText(dto.getMobileNum())
				&& !StringUtil.isMatch(dto.getMobileNum(), "[0-9]{6,11}")) {
			sb.append("[手机号码格式不合法]");
		}
//		if (StringUtil.hasText(dto.getOfficeTel())
//				&& !StringUtil
//						.isMatch(dto.getOfficeTel(),
//								"1([\\d]{10})|((\\+[0-9]{2,4})?\\(?[0-9]+\\)?-?)?[0-9]{7,8}")) {
//			sb.append("[办公电话号码格式不合法]");
//		}
		if (!StringUtil.hasText(dto.getName())) {
			sb.append("[姓名不可为空]");
		}
		return sb.toString();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * cn.edu.tsinghua.cic.ccss.bo.CadreBo#export(cn.edu.tsinghua.cic.ccss.qo
	 * .CadreListQo)
	 */
	@Override
	@Transactional
	public List<CadreDto4Export> export(CadreListQo qo) {
		QueryInfo qi = QueryObjectHelper.buildQueryInfo(qo);
		List<Cadre> list = hibernateDao.findEntities(qi);
		if (CollectionUtil.isEmpty(list)) {
			LogUtil.warn(log, "符合条件的干部导出数据为空");
			return new ArrayList<CadreDto4Export>();
		}
		List<CadreDto4Export> dtoResult = new ArrayList<CadreDto4Export>(
				list.size());
		for (Cadre entity : list) {
			CadreDto4Export dto = new CadreDto4Export();
			dto = decrypt(dto, entity);
			dtoResult.add(dto);
		}
		return dtoResult;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * cn.edu.tsinghua.cic.ccss.bo.CadreBo#exportSignInTable(java.lang.Long)
	 */
	@Override
	@Transactional
	public List<CadreDto4ExportSignIn> exportSignInTable(Long courseId) {
		String hql = "SELECT cadreId FROM CourseSelection WHERE courseId=:courseId AND deletedCardNum='0'";
		Object[] cadreIds = hibernateDao.findObjectArray(hql,
				Param.getCommonParam("courseId", courseId, Type.LONG));
		if (ArrayUtil.isEmpty(cadreIds)) {
			return new ArrayList<CadreDto4ExportSignIn>();
		}
		List<CadreDto4ExportSignIn> dtoResult = new ArrayList<CadreDto4ExportSignIn>(
				cadreIds.length);

		hql = "FROM Cadre WHERE id IN (:cadreIds)";
		List<Cadre> entities = hibernateDao.findEntities(hql, true,
				Param.getCommonParam("cadreIds", cadreIds, Type.ARRAY));
		if (CollectionUtil.isEmpty(entities)) {
			return new ArrayList<CadreDto4ExportSignIn>();
		}

		for (Cadre cadre : entities) {
			CadreDto4ExportSignIn dto = new CadreDto4ExportSignIn();
			dto = decrypt(dto, cadre);
			dtoResult.add(dto);
		}
		return dtoResult;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * cn.edu.tsinghua.cic.ccss.bo.CadreBo#queryCadreDtoPage(cn.edu.tsinghua
	 * .cic.ccss.qo.CadreListQo)
	 */
	@Override
	@Transactional(readOnly = true)
	public DtoResultWithPageInfo<CadreDto> queryCadreDtoPage(CadreListQo qo,
			int page) {
		QueryInfo qi = QueryObjectHelper.buildQueryInfo(qo);
		qi.setSelect(Select.getCountSelect("id"));
		long totalEntity = hibernateDao.getCount(qi);
		if (totalEntity == 0) {
			return new DtoResultWithPageInfo<CadreDto>(
					new ArrayList<CadreDto>(), null);
		}

		PageInfo pi = PageInfo.getInstance(page,
				systemSettingBo.getIntValue("DEFAULT_PAGE_SIZE"), totalEntity);
		qi.setFirstResult(pi.getFirstResultNum());
		qi.setMaxResult(pi.getPageSize());
		qi.setPage(true);
		qi.setSelect(null);
		qi.setUseCache(true);

		List<Cadre> result = hibernateDao.findEntities(qi);
		List<CadreDto> dtoList = new ArrayList<CadreDto>(result.size());
		for (Cadre cadre : result) {
			CadreDto dto = new CadreDto();
			dto = decrypt(dto, cadre);
			dtoList.add(dto);
		}

		return new DtoResultWithPageInfo<CadreDto>(dtoList, pi);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * cn.edu.tsinghua.cic.ccss.bo.CadreBo#queryCadreDtoPage4Selection(cn.edu
	 * .tsinghua.cic.ccss.qo.CadreListQo, int)
	 */
	// @Override
	// @Transactional(readOnly = true)
	// public DtoResultWithPageInfo<CadreDto> queryCadreDtoPage4Selection(
	// CadreListQo qo, int page) {
	// QueryInfo qi = QueryObjectHelper.buildQueryInfo(qo);
	// qi.setSelect(Select.getCountSelect("id"));
	// long totalEntity = hibernateDao.getCount(qi);
	// if (totalEntity == 0) {
	// return new DtoResultWithPageInfo<CadreDto>(
	// new ArrayList<CadreDto>(), null);
	// }
	// PageInfo pi = PageInfo.getInstance(page, 50, totalEntity);
	// qi.setFirstResult(pi.getFirstResultNum());
	// qi.setMaxResult(pi.getPageSize());
	// qi.setPage(true);
	// qi.setSelect(null);
	//
	// List<Cadre> result = hibernateDao.findEntities(qi);
	// List<CadreDto> dtoList = new ArrayList<CadreDto>(result.size());
	// for (Cadre cadre : result) {
	// CadreDto dto = new CadreDto();
	// dto = decrypt(dto, cadre);
	// dtoList.add(dto);
	// }
	//
	// return new DtoResultWithPageInfo<CadreDto>(dtoList, pi);
	// }

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.edu.tsinghua.cic.ccss.bo.CadreBo#doDeleteEntity(java.lang.Long)
	 */
	@Override
	@Transactional
	public void doDeleteEntity(Long id) {
		Cadre entity = this.hibernateDao.load(Cadre.class, id);
		String cardNum = TripletsDESUtil.decrypt(
				systemSettingBo.getStringValue("CURRENT_TRIPLETS_DES_KEY"),
				entity.getCardNum());
		String hql = "update CourseSelection SET deletedCardNum=:cardNum where cadreId=:id";
		hibernateDao.executeUpdate(hql,
				Param.getCommonParam("cardNum", cardNum, Type.STRING),
				Param.getCommonParam("id", id, Type.LONG));
		hql = "update CourseCanceled SET deletedCardNum=:cardNum where cadreId=:id";
		hibernateDao.executeUpdate(hql,
				Param.getCommonParam("cardNum", cardNum, Type.STRING),
				Param.getCommonParam("id", id, Type.LONG));
		this.hibernateDao.delete(entity);
		String msg = "";
		try {
			msg = BoHelper.synRoleToAuth(cardNum);
		} catch (MalformedURLException e) {
			LogUtil.warn(log, "[同步用户角色失败: %s]", msg);
		} catch (Exception e) {
			LogUtil.warn(log, "[同步用户角色失败: %s]", msg);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.edu.tsinghua.cic.ccss.bo.CadreBo#encryptDataWithNewKey()
	 */
	@Override
	@Transactional
	public void encryptDataWithNewKey() {
		String oldKey = systemSettingBo
				.getStringValue("CURRENT_TRIPLETS_DES_KEY");
		String newKey = TripletsDESUtil.generateKey();
		List<Cadre> list = hibernateDao.findEntities("FROM Cadre", true);
		if (CollectionUtil.isEmpty(list)) {
			return;
		}
		List<Cadre> newList = new ArrayList<Cadre>(list.size());
		for (Cadre cadre : list) {
			newList.add(getNewCadreData(cadre, oldKey, newKey));
		}

		hibernateDao.update(newList.toArray(new Cadre[newList.size()]));
		SystemSetting oldKeyEntity = hibernateDao.load(SystemSetting.class,
				"OLD_TRIPLETS_DES_KEY");
		SystemSetting newKeyEntity = hibernateDao.load(SystemSetting.class,
				"CURRENT_TRIPLETS_DES_KEY");
		oldKeyEntity.setValue(oldKey);
		newKeyEntity.setValue(newKey);
		hibernateDao.update(oldKeyEntity, newKeyEntity);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.edu.tsinghua.cic.ccss.bo.CadreBo#initCredit()
	 */
	@Override
	@Transactional
	public void initCredit() {
		LogUtil.info(log, "重置当月学时总数下月学时总数，下月学时总数为0");
		String hql = "update Cadre SET currentMonthTotalCredit=nextMonthTotalCredit, nextMonthTotalCredit=0";
		hibernateDao.executeUpdate(hql);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.edu.tsinghua.cic.ccss.bo.CadreBo#getCreditInfo(java.lang.String)
	 */
	@Override
	@Transactional
	public int[] getCreditInfo(String cardNum) {
		String cardNumMD5 = MD5Util.encrypt(cardNum);
		Cadre cadre = hibernateDao.findByUniqueFieldValue(Cadre.class,
				"cardNumMD5",
				Param.getCommonParam("cardNumMD5", cardNumMD5, Type.STRING));
		if (cadre == null) {
			return new int[] { 0, 0, 0, 0, 0 };
		}
		String isNewFlag = cadre.getIsNewFlag();
		String jobLevel = TripletsDESUtil.decrypt(
				systemSettingBo.getStringValue("CURRENT_TRIPLETS_DES_KEY"),
				cadre.getJobLevel());
		int max = 0;
		if (isNewFlag.equals("1")) {
			max = systemSettingBo.getIntValue("NEW_CADRE_MAX_CREDIT_OF_MONTH");
		} else if (jobLevel.equals("1")) {
			max = systemSettingBo.getIntValue("LEVEL_ONE_MAX_CREDIT_OF_MONTH");
		} else if (jobLevel.equals("2")) {
			max = systemSettingBo.getIntValue("LEVEL_TWO_MAX_CREDIT_OF_MONTH");
		} else if (jobLevel.equals("3")) {
			max = systemSettingBo
					.getIntValue("LEVEL_THREE_MAX_CREDIT_OF_MONTH");
		} else if (jobLevel.equals("4")) {
			max = systemSettingBo.getIntValue("LEVEL_FOUR_MAX_CREDIT_OF_MONTH");
		} else if (jobLevel.equals("5")) {
			max = systemSettingBo.getIntValue("LEVEL_FIVE_MAX_CREDIT_OF_MONTH");
		} else if (jobLevel.equals("6")) {
			max = systemSettingBo.getIntValue("LEVEL_SIX_MAX_CREDIT_OF_MONTH");
		} else if (jobLevel.equals("7")) {
			max = systemSettingBo
					.getIntValue("LEVEL_SEVEN_MAX_CREDIT_OF_MONTH");
		}
		int currentCredit = cadre.getCurrentMonthTotalCredit();
		int nextCredit = cadre.getNextMonthTotalCredit();
		int sub = max - currentCredit;
		int nextSub = max - nextCredit;

		sub = sub < 0 ? 0 : sub;
		nextSub = nextSub < 0 ? 0 : nextSub;
		return new int[] { max, currentCredit, sub, nextCredit, nextSub };
	}

	// 用新密钥重新加密干部数据
	private Cadre getNewCadreData(Cadre cadre, String oldKey, String newKey) {
		if (StringUtil.hasText(cadre.getCardNum())) {
			String value = TripletsDESUtil.decrypt(oldKey, cadre.getCardNum());
			cadre.setCardNum(TripletsDESUtil.encrypt(newKey, value));
		}
		if (StringUtil.hasText(cadre.getEmail())) {
			String value = TripletsDESUtil.decrypt(oldKey, cadre.getEmail());
			cadre.setEmail(TripletsDESUtil.encrypt(newKey, value));
		}
		if (StringUtil.hasText(cadre.getJobLevel())) {
			String value = TripletsDESUtil.decrypt(oldKey, cadre.getJobLevel());
			cadre.setJobLevel(TripletsDESUtil.encrypt(newKey, value));
		}
		if (StringUtil.hasText(cadre.getMobileNum())) {
			String value = TripletsDESUtil
					.decrypt(oldKey, cadre.getMobileNum());
			cadre.setMobileNum(TripletsDESUtil.encrypt(newKey, value));
		}
		if (StringUtil.hasText(cadre.getName())) {
			String value = TripletsDESUtil.decrypt(oldKey, cadre.getName());
			cadre.setName(TripletsDESUtil.encrypt(newKey, value));
		}
		if (StringUtil.hasText(cadre.getOfficeTel())) {
			String value = TripletsDESUtil
					.decrypt(oldKey, cadre.getOfficeTel());
			cadre.setOfficeTel(TripletsDESUtil.encrypt(newKey, value));
		}
		if (StringUtil.hasText(cadre.getUnitName())) {
			String value = TripletsDESUtil.decrypt(oldKey, cadre.getUnitName());
			cadre.setUnitName(TripletsDESUtil.encrypt(newKey, value));
		}
		if (StringUtil.hasText(cadre.getDuty())) {
			String value = TripletsDESUtil.decrypt(oldKey, cadre.getDuty());
			cadre.setDuty(TripletsDESUtil.encrypt(newKey, value));
		}
		if (StringUtil.hasText(cadre.getDuty())) {
			String value = TripletsDESUtil.decrypt(oldKey, cadre.getDuty());
			cadre.setDuty(TripletsDESUtil.encrypt(newKey, value));
		}
		if (StringUtil.hasText(cadre.getParty())) {
			String value = TripletsDESUtil.decrypt(oldKey, cadre.getParty());
			cadre.setParty(TripletsDESUtil.encrypt(newKey, value));
		}
		if (StringUtil.hasText(cadre.getNation())) {
			String value = TripletsDESUtil.decrypt(oldKey, cadre.getNation());
			cadre.setNation(TripletsDESUtil.encrypt(newKey, value));
		}
		if (StringUtil.hasText(cadre.getEducation())) {
			String value = TripletsDESUtil
					.decrypt(oldKey, cadre.getEducation());
			cadre.setEducation(TripletsDESUtil.encrypt(newKey, value));
		}
		if (StringUtil.hasText(cadre.getBirthday())) {
			String value = TripletsDESUtil.decrypt(oldKey, cadre.getBirthday());
			cadre.setBirthday(TripletsDESUtil.encrypt(newKey, value));
		}
		if (StringUtil.hasText(cadre.getTitles())) {
			String value = TripletsDESUtil.decrypt(oldKey, cadre.getTitles());
			cadre.setTitles(TripletsDESUtil.encrypt(newKey, value));
		}
		if (StringUtil.hasText(cadre.getPostTime())) {
			String value = TripletsDESUtil.decrypt(oldKey, cadre.getPostTime());
			cadre.setPostTime(TripletsDESUtil.encrypt(newKey, value));
		}
		return cadre;
	}

	// 解密实体对象为DTO对象
	private <DTO extends SuperCadreDto> DTO decrypt(DTO dto, Cadre entity) {
		String key = systemSettingBo.getStringValue("CURRENT_TRIPLETS_DES_KEY");
		
		BeanPropertyUtil.copy(dto, entity);
		if (StringUtil.hasText(dto.getCardNum()))
			dto.setCardNum(TripletsDESUtil.decrypt(key, dto.getCardNum()));
		if (StringUtil.hasText(dto.getEmail()))
			dto.setEmail(TripletsDESUtil.decrypt(key, dto.getEmail()));
		if (StringUtil.hasText(dto.getJobLevel()))
			dto.setJobLevel(TripletsDESUtil.decrypt(key, dto.getJobLevel()));
		if (StringUtil.hasText(dto.getMobileNum()))
			dto.setMobileNum(TripletsDESUtil.decrypt(key, dto.getMobileNum()));
		if (StringUtil.hasText(dto.getName()))
			dto.setName(TripletsDESUtil.decrypt(key, dto.getName()));
		if (StringUtil.hasText(dto.getOfficeTel()))
			dto.setOfficeTel(TripletsDESUtil.decrypt(key, dto.getOfficeTel()));
		if (StringUtil.hasText(dto.getUnitName()))
			dto.setUnitName(TripletsDESUtil.decrypt(key, dto.getUnitName()));
		if (StringUtil.hasText(dto.getDuty()))
			dto.setDuty(TripletsDESUtil.decrypt(key, dto.getDuty()));
		if (StringUtil.hasText(dto.getNation()))
			dto.setNation(TripletsDESUtil.decrypt(key, dto.getNation()));
		if (StringUtil.hasText(dto.getEducation()))
			dto.setEducation(TripletsDESUtil.decrypt(key, dto.getEducation()));
		if (StringUtil.hasText(dto.getParty()))
			dto.setParty(TripletsDESUtil.decrypt(key, dto.getParty()));
		if (StringUtil.hasText(dto.getBirthday()))
			dto.setBirthday(TripletsDESUtil.decrypt(key, dto.getBirthday()));
		if (StringUtil.hasText(entity.getPostTime()))
			dto.setPostTime(TripletsDESUtil.decrypt(key, entity.getPostTime()));
		if (StringUtil.hasText(entity.getTitles()))
			dto.setTitles(TripletsDESUtil.decrypt(key, entity.getTitles()));
		return dto;
	}

	// 加密DTO对象为实体对象
	private <DTO extends GeneralDto> Cadre encrypt(DTO dto, Cadre entity) {
		String key = systemSettingBo.getStringValue("CURRENT_TRIPLETS_DES_KEY");

		BeanPropertyUtil.copy(entity, dto);
		if (StringUtil.hasText(entity.getCardNum())) {
			entity.setCardNumMD5(MD5Util.encrypt(entity.getCardNum()));
			entity.setCardNum(TripletsDESUtil.encrypt(key, entity.getCardNum()));
		}
		if (StringUtil.hasText(entity.getName())) {
			entity.setNameMD5(MD5Util.encrypt(entity.getName()));
			entity.setName(TripletsDESUtil.encrypt(key, entity.getName()));
		}
		if (StringUtil.hasText(entity.getJobLevel())) {
			entity.setJobLevelMD5(MD5Util.encrypt(entity.getJobLevel()));
			entity.setJobLevel(TripletsDESUtil.encrypt(key,
					entity.getJobLevel()));
		}
		if (StringUtil.hasText(entity.getEmail()))
			entity.setEmail(TripletsDESUtil.encrypt(key, entity.getEmail()));
		if (StringUtil.hasText(entity.getMobileNum()))
			entity.setMobileNum(TripletsDESUtil.encrypt(key,
					entity.getMobileNum()));
		if (StringUtil.hasText(entity.getOfficeTel()))
			entity.setOfficeTel(TripletsDESUtil.encrypt(key,
					entity.getOfficeTel()));
		if (StringUtil.hasText(entity.getUnitName()))
			entity.setUnitName(TripletsDESUtil.encrypt(key,
					entity.getUnitName()));
		if (StringUtil.hasText(entity.getDuty()))
			entity.setDuty(TripletsDESUtil.encrypt(key, entity.getDuty()));

		if (StringUtil.hasText(entity.getBirthday()))
			entity.setBirthday(TripletsDESUtil.encrypt(key,
					entity.getBirthday()));
		if (StringUtil.hasText(entity.getEducation()))
			entity.setEducation(TripletsDESUtil.encrypt(key,
					entity.getEducation()));
		if (StringUtil.hasText(entity.getNation()))
			entity.setNation(TripletsDESUtil.encrypt(key, entity.getNation()));
		if (StringUtil.hasText(entity.getParty()))
			entity.setParty(TripletsDESUtil.encrypt(key, entity.getParty()));
		if (StringUtil.hasText(entity.getPostTime()))
			entity.setPostTime(TripletsDESUtil.encrypt(key,
					entity.getPostTime()));
		if (StringUtil.hasText(entity.getTitles()))
			entity.setTitles(TripletsDESUtil.encrypt(key, entity.getTitles()));
		return entity;
	}
}
